package com.tutou.ikuser.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.tutou.ikuser.filter.JwtAuthenticationFilter;
import com.tutou.ikuser.mapper.UserMapper;
import com.tutou.ikuser.pojo.dto.Result;
import com.tutou.ikuser.pojo.dto.UserDTO;
import com.tutou.ikuser.pojo.po.User;
import com.tutou.ikuser.service.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserInfoImpl implements UserInfo {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result getInfoById(String token) {
        Map<Object, Object> userMsg = stringRedisTemplate.opsForHash().entries(token);
        UserDTO user = BeanUtil.copyProperties(userMsg, UserDTO.class);
        user.setPassword(null);
        return Result.ok(user);
    }

    @Override
    public Result updateUserInfo(String token, User user) {
        Map<Object, Object> userMsg = stringRedisTemplate.opsForHash().entries(token);
        User certification = BeanUtil.copyProperties(userMsg, User.class);
        user.setUserId(certification.getUserId()).setPassword(certification.getPassword()).setPhone(certification.getPhone());
        userMapper.update(user);
        Map<String, Object> userMap = BeanUtil.beanToMap(user, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        stringRedisTemplate.opsForHash().putAll(token, userMap);
        return Result.ok("修改信息成功~");
    }
}
